import threading
import time
# 共享资源
count = 0
# 创建锁对象
lock = threading.Lock()
def increment():
    global count
    for _ in range(1000000):
        # 获取锁
        lock.acquire()
        try:
            # 临界区：操作共享资源
            count += 1
        finally:
            # 确保锁一定会被释放
            lock.release()
# 创建两个线程
t1 = threading.Thread(target=increment)
t2 = threading.Thread(target=increment)
# 启动线程
t1.start()
t2.start()
# 等待线程结束
t1.join()
t2.join()
# 预期结果是 2000000
print(f"最终结果: {count}")


import threading
import time

# 定义线程要执行的函数
def print_numbers():
    for i in range(5):
        time.sleep(1)  # 暂停1秒
        print(f"数字: {i}")

def print_letters():
    for letter in ['A', 'B', 'C', 'D', 'E']:
        time.sleep(1)  # 暂停1秒
        print(f"字母: {letter}")

# 创建线程
t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_letters)

# 启动线程
t1.start()
t2.start()

# 等待线程结束
t1.join()
t2.join()

print("所有线程执行完毕")